package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInConfigService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住表Service业务层处理
 * 
 * @author zzyl
 * @date 2025-02-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    private static  Integer sortOrder=1;


    /**
     * 查询入住表
     * 
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住表列表
     * 
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住表
     * 
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo detailId(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住表信息并封装家属信息
        CheckIn checkIn=selectCheckIn(checkInDetailVo,id);
        //查询老人表信息并封装
        selectCheckInElderVo(checkInDetailVo,checkIn.getElderId());
        //查询入住配置信息
        selectCheckInConfig(checkInDetailVo,checkIn);
        //查询入住合同
        selectContract(checkInDetailVo,checkIn.getElderId());
        return checkInDetailVo;
    }
    //查询入住合同
    private void selectContract(CheckInDetailVo checkInDetailVo, Long elderId) {
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        if (ObjectUtil.isNotNull(contract)){
            checkInDetailVo.setContract(contract);
        }
    }

    /**
     * 查询入住配置信息
     *
     * @param checkInDetailVo 查询入住配置信息
     * @param checkIn 入住表信息
     */
    private void selectCheckInConfig(CheckInDetailVo checkInDetailVo, CheckIn checkIn) {
       CheckInConfig checkInConfig=checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        if (ObjectUtil.isNotNull(checkInConfig)){
            checkInDetailVo.setCheckInConfigVo(BeanUtil.copyProperties(checkInConfig, CheckInConfigVo.class));
            checkInDetailVo.getCheckInConfigVo().setBedNumber(checkIn.getBedNumber());
            checkInDetailVo.getCheckInConfigVo().setStartDate(checkIn.getStartDate());
            checkInDetailVo.getCheckInConfigVo().setEndDate(checkIn.getEndDate());
        }
    }

    /**
     * 查询入住表信息并封装家属信息
     * @param checkInDetailVo 入住响应信息
     * @param id           入住id
     * @return 结果
     */
    private CheckIn selectCheckIn(CheckInDetailVo checkInDetailVo, Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        if (ObjectUtil.isNotNull(checkIn)){
            checkInDetailVo.setElderFamilyVoList(JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class));
        }
        return checkIn;
    }

    /**
     *查询老人表信息并封装
     */
    private void selectCheckInElderVo(CheckInDetailVo checkInDetailVo, Long id) {
        Elder elder = elderMapper.selectElderById(id);
        if (ObjectUtil.isNotNull(elder)){
            checkInDetailVo.setCheckInElderVo( BeanUtil.copyProperties(elder, CheckInElderVo.class));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        //1.判断老人是否入住过
       Elder elder= selectByIdCardNo(checkInElderDto.getIdCardNo());
      //2.更新床位信息
        Bed bed=updateBedStatus(checkInApplyDto.getCheckInConfigDto().getBedId(),1);
        //3.新增或更新老人信息
       elder= insertOrUpdate(elder,checkInElderDto,bed);
       //4.新增签约办理
        insertContract(elder,checkInApplyDto);
        //5.新增入住信息
        Long checkInId = insertCheckIns(elder,checkInApplyDto);
        //6.新增入住配置信息
        insertCheckInConfig(checkInId,checkInApplyDto.getCheckInConfigDto());
    }

    /**
     * 新增入住配置信息
     */
    private void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfig.setSortOrder(sortOrder++);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    private Long insertCheckIns(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkIn);
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        if (ObjectUtil.isNotNull(elderFamilyDtoList)){
            checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        }
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(sortOrder++);
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    /**
     * 新增签约办理
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(1);
        contract.setContractNumber("");
        contract.setSortOrder(sortOrder++);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     * @param elder
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdate(Elder elder, CheckInElderDto checkInElderDto, Bed bed) {

        if (ObjectUtil.isNull(elder)){
            elder=new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);
        }else {
            elder.setBedId(bed.getId());
            elder.setStatus(1);
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     *  更新床位状态
     * @param bedId
     * @param status
     * @return
     */
    private Bed updateBedStatus(Long bedId, int status) {
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(status);
        bedMapper.updateById(bed);
        return bed;
    }

    /**
     *  根据身份证号查询老人
     * @param idCardNo
     * @return
     */
    private Elder selectByIdCardNo(String idCardNo) {
        return elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo,idCardNo));
    }

    /**
     * 删除入住表信息
     * 
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
}
